import requests
import base64
from bs4 import BeautifulSoup
from jira import JIRA
from Seatalk.sendMessage import send_message_to_all
from logger import *


class check_material:
    """检查ID市场物料是否齐全"""

    def __init__(self, username, password, release_jira_url, test_summary_url):
        self.username = username
        self.password = password
        self.release_jira_url = release_jira_url  # release单的url
        self.test_summary_url = test_summary_url  # 检查面板的url
        self.issue_dict = {}  # 检查面板信息解析至此字典
        self.count_error = 0  # 物料异常数量
        self.version = ''  # 版本
        self.jira = JIRA(server='https://jira.shopee.io/', auth=(username, password))
        html_text = self.get_test_summary()
        self.parse_test_summary(html_text)
        self.get_version()

    def get_test_summary(self):
        """获取检查面板的html信息"""
        Authorization = f"{self.username}:{self.password}".encode('UTF-8')
        headers = {
            "Content-Type": "application/json",
            "Authorization": 'Basic ' + str(base64.b64encode(Authorization), 'utf-8')
        }
        r = requests.get(url=self.test_summary_url, headers=headers)
        return r.text

    def parse_test_summary(self, html_text):
        """解析检查面板的html信息至字典"""
        soup = BeautifulSoup(html_text, features="html.parser")
        tables = soup.findAll('table')
        tab = tables[0]
        self.issue_dict = {}
        for idx, tr in enumerate(tab.findAll('tr')):
            if idx != 0:
                if len(tr.findAll('td')) == 8:
                    # if (idx - 1) % 8 == 0:  一旦物料面板结构发生变化，此判断方法就会导致异常
                    Ticket, test_type, reporter, test_review_result, test_review_case, test_review_proof, Sync_URL, notes = tr.findAll(
                        'td')
                    self.issue_dict[Ticket.a.string] = {}
                else:
                    test_type, reporter, test_review_result, test_review_case, test_review_proof, Sync_URL, notes = tr.findAll(
                        'td')
                self.issue_dict[Ticket.a.string][test_type.string] = {}
                self.issue_dict[Ticket.a.string][test_type.string]["Reporter"] = reporter
                self.issue_dict[Ticket.a.string][test_type.string]["Test/Review Result"] = test_review_result
                self.issue_dict[Ticket.a.string][test_type.string]["Test/Review Case"] = test_review_case
                self.issue_dict[Ticket.a.string][test_type.string]["Test/Review Proof"] = test_review_proof
                self.issue_dict[Ticket.a.string][test_type.string]["Sync URL"] = Sync_URL
                self.issue_dict[Ticket.a.string][test_type.string]["Notes"] = notes

    def get_version(self):
        """获取版本信息"""
        issue = self.jira.issue(self.release_jira_url.split('/')[-1])
        self.version = issue.fields.fixVersions[0].name

    def check_sit_test_report(self, key):
        """检查SIT Test Report物料是否缺失"""
        result_flag = True
        test_review_result = self.issue_dict[key]['SIT Test Report']['Test/Review Result'].getText()

        # Test/Review Result 是否正确
        if test_review_result.find("Tested by me, result passed") > -1:
            pass
        elif test_review_result.find("Testing skipped") > -1:
            pass
        else:
            PRINTE(f"{key} sit测试物料未上传 -> xunjie.yin@shopee.com")
            self.count_error += 1
            result_flag = False
        return result_flag

    def check_uat_test_report(self, key):
        """检查UAT Test Report物料是否缺失"""
        result_flag = True
        test_review_result = self.issue_dict[key]['UAT Test Report']['Test/Review Result'].getText()

        # Test/Review Result 是否正确
        if test_review_result.find("Tested by someone else, signoff attached") > -1:
            pass
        elif test_review_result.find("Tested by me, result passed") > -1:
            pass
        elif test_review_result.find("Testing skipped") > -1:
            pass
        else:
            issue = self.jira.issue(key)
            reporter = issue.fields.reporter.name
            PRINTE(f"{key} uat测试物料未上传 -> {reporter}")
            self.count_error += 1
            result_flag = False
        return result_flag

    def check_PRD_Sign_Off_report(self, key):
        """检查PRD/TRD Sign-Off物料是否缺失"""
        result_flag = True
        test_review_result = self.issue_dict[key]['PRD/TRD Sign-Off']['Test/Review Result'].getText()
        if test_review_result.find("Reviewed by someone else, signoff attached") > -1:
            pass
        elif test_review_result.find("Reviewed by me, result passed") > -1:
            pass
        elif test_review_result.find("Reviewing skipped") > -1:
            pass
        else:
            issue = self.jira.issue(key)
            reporter = issue.fields.reporter.name
            PRINTE(f"{key} PRD Sign-Off 物料未上传 -> {reporter}")
            self.count_error += 1
            result_flag = False
        return result_flag

    def check_Tech_design_and_review_report(self, key):
        """检查Technical Design and Review Report物料是否缺失"""
        result_flag = True
        Test_Review_Case = self.issue_dict[key]['Technical Design and Review Report']['Test/Review Case'].getText()
        test_review_result = self.issue_dict[key]['PRD/TRD Sign-Off']['Test/Review Result'].getText()

        if Test_Review_Case.find("https://") > -1 or test_review_result.find("Reviewing skipped") > -1:
            notes = self.issue_dict[key]['Technical Design and Review Report']['Notes'].getText()
            if notes.upper().find('DEV') == -1:
                PRINTE(f"{key} Technical 物料中缺 DEV Approved -> huadong.zhou@shopee.com、wubo.cao@shopee.com")
                self.count_error += 1
                result_flag = False
            if notes.find('PM') == -1:
                issue = self.jira.issue(key)
                summary = issue.fields.summary
                if summary.find('Tech') > -1:
                    pass
                else:
                    reporter = issue.fields.reporter.name
                    PRINTE(f"{key} Technical 物料中缺 PM Approved -> {reporter}")
                    self.count_error += 1
                    result_flag = False
            if notes.find('QA') == -1:
                PRINTE(f"{key} Technical 物料中缺 QA Approved -> xueqin.wang@shopee.com")
                self.count_error += 1
                result_flag = False
            if notes.find('SEC') == -1:
                PRINTE(f"{key} Technical 物料中缺 SEC Approved -> qin.yinyq@shopee.com")
                self.count_error += 1
                result_flag = False
        else:
            PRINTE(f"{key} Technical Report 物料缺少 -> huadong.zhou@shopee.com、wubo.cao@shopee.com")
            self.count_error += 1
            result_flag = False
        return result_flag

    def check_security_report(self, key):
        """检查安全物料是否缺失"""
        result_flag = True
        test_review_result = self.issue_dict[key]['Security Code Scan Report']['Test/Review Result'].getText()
        if test_review_result.find("Reviewed by me, result passed") > -1:
            pass
        elif test_review_result.find("Reviewing skipped") > -1:
            pass
        else:
            PRINTE(f"{key} 安全物料缺少 -> qin.yinyq@shopee.com")
            self.count_error += 1
            result_flag = False
        return result_flag

    def check_regression_report(self, key):
        """检查回归测试报告物料是否缺失"""
        result_flag = True
        test_review_result = self.issue_dict[key]['Regression Test Report']['Test/Review Result'].getText()

        # Test/Review Result 是否正确'
        if test_review_result.find("Tested by me, result passed") > -1:
            # 检查Test/Review Case是否上传
            # test_review_case = self.issue_dict[key]['Regression Test Report']['Test/Review Case']
            # test_case_regexp = re.compile("DWH.*regression_testCase")
            # if test_review_case.find('a', text=test_case_regexp):
            #     PRINTS(f"{key} Regression测试案例上传成功")
            #     pass
            # else:
            #     PRINTE(f"{key} Regression测试案例未上传")
            #     self.count_error += 1
            #     result_flag = False

            # 检查 Test/Review Proof 是否上传
            # test_review_proof = self.issue_dict[key]['Regression Test Report']['Test/Review Proof']
            # test_proof_regexp = re.compile("DWH.*regression_testReport")
            # if test_review_proof.find('a', text=test_proof_regexp):
            #     # PRINTS(f"{key} Regression Test/Review Proof 上传成功")
            #     pass
            # else:
            #     PRINTE(f"{key} Regression Test/Review Proof 未上传")
            #     self.count_error += 1
            #     result_flag = False
            pass
        else:
            PRINTE(f"{key} Regression测试物料未上传 -> xueqin.wang@shopee.com")
            self.count_error += 1
            result_flag = False
        return result_flag

    def print_result(self):
        """打印检查结果"""
        print()
        if self.count_error > 0:
            PRINTE(f"{self.version} 共有 {self.count_error} 个物料缺失")
        else:
            PRINTS(f"xueqin.wang@shopee.com\n{self.version} 物料齐全, Please acknowledge this report !")

        PRINTI(f"\nRelease: {self.release_jira_url}")
        PRINTI(f"检查面板: {self.test_summary_url}")

    def first_push_material(self):
        """首次发送催促物料消息给群里所有人"""
        # text = f"\n大家好，请补充 ID-{self.version}版本的物料，谢谢。\n备注：UAT及PRD Sign-Off物料尽量在本周五完成。\nRelease: {self.release_jira_url}\n检查面板: {self.test_summary_url}"
        text = f"\n大家好，请补充 ID-{self.version}版本的物料，谢谢。\n\nRelease: {self.release_jira_url}\n检查面板: {self.test_summary_url}"
        send_message_to_all(text)
